package com.atguigu.mall.seckill.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/** 自定义阻塞返回方法 */
@Configuration
public class mallSeckillSentinelConfig {

  public mallSeckillSentinelConfig() {
    WebCallbackManager.setUrlBlockHandler(
            (request, response, ex) -> {
              R error =
                  R.error(
                      BizCodeEnume.TO_MANY_REQUEST.getCode(), BizCodeEnume.TO_MANY_REQUEST.getMsg());
              response.setCharacterEncoding("UTF-8");
              response.setContentType("application/json");
              response.getWriter().write(JSON.toJSONString(error));
            });
  }
}
